const STORAGE_KEYS = {
  CONNECTIONS: 'influxdb_connections',
  QUERY_HISTORY: 'influxdb_query_history',
  SETTINGS: 'influxdb_settings'
}

class StorageService {
  saveConnections(connections) {
    try {
      localStorage.setItem(STORAGE_KEYS.CONNECTIONS, JSON.stringify(connections))
      return true
    } catch (error) {
      console.error('Failed to save connections:', error)
      return false
    }
  }

  loadConnections() {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.CONNECTIONS)
      return data ? JSON.parse(data) : []
    } catch (error) {
      console.error('Failed to load connections:', error)
      return []
    }
  }

  saveQueryHistory(queries) {
    try {
      const MAX_HISTORY = 100
      const trimmedQueries = queries.slice(-MAX_HISTORY)
      localStorage.setItem(STORAGE_KEYS.QUERY_HISTORY, JSON.stringify(trimmedQueries))
      return true
    } catch (error) {
      console.error('Failed to save query history:', error)
      return false
    }
  }

  loadQueryHistory() {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.QUERY_HISTORY)
      return data ? JSON.parse(data) : []
    } catch (error) {
      console.error('Failed to load query history:', error)
      return []
    }
  }

  addQueryToHistory(query) {
    const history = this.loadQueryHistory()
    const newEntry = {
      query,
      timestamp: new Date().toISOString(),
      id: Date.now()
    }
    history.push(newEntry)
    this.saveQueryHistory(history)
    return newEntry
  }

  saveSettings(settings) {
    try {
      localStorage.setItem(STORAGE_KEYS.SETTINGS, JSON.stringify(settings))
      return true
    } catch (error) {
      console.error('Failed to save settings:', error)
      return false
    }
  }

  loadSettings() {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.SETTINGS)
      return data ? JSON.parse(data) : {
        theme: 'light',
        editorTheme: 'material',
        fontSize: 14,
        autoComplete: true
      }
    } catch (error) {
      console.error('Failed to load settings:', error)
      return {
        theme: 'light',
        editorTheme: 'material',
        fontSize: 14,
        autoComplete: true
      }
    }
  }
}

export default new StorageService()